<script setup name="updateDialog" lang="ts">
import { ref, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { deptAddApi, deptUpdateApi } from '@/apis/dept'

interface Props {
  visible: boolean,
  info: {
    type: object,
    default: () => void
  },
  /** 上级id */
  pid: {
    type: number,
    default: 0
  }
}

const props = defineProps<Props>()
const emit = defineEmits(['confirm', 'update:visible'])

watch(props, (prop) => {
  if (prop.visible && prop.info._id) {
    formData.value = {deptName:prop.info.deptName, id: prop.info._id }
  }
})

/** form 表单 */
const formData = ref({
  deptName: ''
})

/** 关闭弹窗 */
const handleClose = () => {
  formData.value = {
    deptName: ''
  }
  emit('update:visible', false)
}

const handleConfirm = async () => {
  const api = formData.value.id? deptUpdateApi : deptAddApi
  const params = formData.value.id? formData.value : {...formData.value, pid: props.pid, deptLevel: props.pid ? 2 : 1 }
  await api(params)
  ElMessage.success('操作成功')
  emit('confirm')
  handleClose()
}
</script>

<template>
  <el-dialog :model-value="visible" title="修改部门信息" width="30%" @close="handleClose">
    <!-- 对话框内容插槽 -->
    <el-form>
      <el-form-item label="部门名称">
        <el-input v-model="formData.deptName" placeholder="请输入部门名称" />
      </el-form-item>
    </el-form>

    <!-- 自定义底部按钮 -->
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
